package com.bangdream.michelia.view.activity.my;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.andview.refreshview.XRefreshView;
import com.bangdream.michelia.R;
import com.bangdream.michelia.contract.CoursesContract;
import com.bangdream.michelia.entity.CertBean;
import com.bangdream.michelia.entity.DownLoadInfo;
import com.bangdream.michelia.presenter.AdPresenter;
import com.bangdream.michelia.presenter.CoursesPresenter;
import com.bangdream.michelia.presenter.base.BasePresenter;
import com.bangdream.michelia.tool.rejava.BaseObserverResponseBodyNormalHttp;
import com.bangdream.michelia.tool.retrofithttp.DownLoadManager;
import com.bangdream.michelia.tool.retrofithttp.RetroFactory;
import com.bangdream.michelia.utils.FileUtil;
import com.bangdream.michelia.utils.L;
import com.bangdream.michelia.utils.MyLog;
import com.bangdream.michelia.utils.PublicResources;
import com.bangdream.michelia.utils.SPUtils;
import com.bangdream.michelia.utils.ToastUtil;
import com.bangdream.michelia.view.activity.base.SwipeBackActivity;
import com.bangdream.michelia.view.adapter.MyCertAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

public class MyCertificate extends SwipeBackActivity<CoursesContract.IMyCertList, CoursesPresenter<CoursesContract.IMyCertList>>
        implements CoursesContract.IMyCertList {
    private XRefreshView refreshView;
    private RecyclerView recyclerView;
    private LinearLayoutManager linearLayoutManager;
    private int page = 1;
    MyCertAdapter adapter;
    private static final int REQUEST_CODE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE" };
    @Override
    public int getLayout() {
        return R.layout.activity_certificate;
    }

    @Override
    public void findId() {
        refreshView = findViewById(R.id.refreshView);
        refreshView.setPullLoadEnable(false);
        refreshView.setPullRefreshEnable(true);
        recyclerView = findViewById(R.id.recyclerView);
        linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        initEmptyView(recyclerView);
        adapter = new MyCertAdapter(R.layout.item_cert);
        recyclerView.setAdapter(adapter);

        refreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh(boolean isPullDown) {
                super.onRefresh(isPullDown);
                page = 1;
                getData();
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                super.onLoadMore(isSilence);
                page++;
                getData();
            }
        });

        getData();
        checkPermission();
    }

    public void getData() {
        adapter.setEmptyView(loadingView);
        mPresenter.getCertList(page, PublicResources.PageSize);
    }

    @Override
    public void setListener() {
        adapter.setOnItemChildClickListener((a, view, position) -> {
            if (ActivityCompat.checkSelfPermission(MyCertificate.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                download(adapter.getData().get(position).getCertPath());
            }else {
                ToastUtil.showShortToast(MyCertificate.this,"获取权限失败");
            }
        });
    }

    @Override
    public void logic() {
        initTitleBar(" ", "我的证书", "", this);
    }

    @Override
    public CoursesPresenter<CoursesContract.IMyCertList> createPresenter() {
        return new CoursesPresenter<>();
    }


    @Override
    public void onClick(View view) {
        super.onClick(view);

    }


    @Override
    public void setCertList(boolean isSuccess, int page, List<CertBean> data) {
//        refreshView.stopRefresh();
//        refreshView.stopLoadMore();
        if (isSuccess && data != null) {
            if (page == 1) {
                if (data.size() == 0) {
                    adapter.setEmptyView(noDataView);
                } else {
                    adapter.setNewData(data);
                    //显示数据大于20条才允许上拉加载更多
                    if (data.size() >= PublicResources.PageSize) {
                        refreshView.setPullLoadEnable(true);
                    }
                }
            } else {
                int tempIndex = adapter.getData().size();
                for (int i = 0; i < data.size(); i++) {
                    adapter.getData().add(data.get(i));
                }
                adapter.notifyItemChanged(tempIndex, adapter.getData().size());
                refreshView.stopLoadMore();
            }
        } else {
            //如果是加载新数据时失败了 则page-1
            if (page > 1) {
                refreshView.stopLoadMore();
                this.page--;
            } else {
                //还是还原为1防止出现负数
                this.page = 1;
                refreshView.stopRefresh();
                adapter.setEmptyView(isSuccess?noDataView:errorView);

            }
        }
    }

    @SuppressLint("CheckResult")
    private void download(String url) {
        Observable apiserice = RetroFactory.getInstance().downloadFile(url);
        apiserice.compose(composeFunction).subscribe(new BaseObserverResponseBodyNormalHttp(null, null) {
            @Override
            public void onHandleSuccess(final ResponseBody t) {
                Observable.create(new ObservableOnSubscribe<String>() {
                    @Override
                    public void subscribe(@NonNull ObservableEmitter<String> e) throws Exception {
                        if(pd!=null){
                            pd.dismiss();
                        }
                        String path = DownLoadManager.writeResponseBodyToDisk(MyCertificate.this, t, new DownLoadInfo());
                        if (path != null && path.length() > 0) {
                            e.onNext(path);
                        } else {
                            e.onNext(null);
                        }
                        e.onComplete();
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {
                    MyLog.d("tag", "下载文件的本地地址为：" + s);
                    ToastUtil.showShortToast(MyCertificate.this,"保存成功,文件夹名为:byl");

                    addMediaStore(MyCertificate.this,new File(DownLoadManager.getSDPath()),s);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//如果是4.4及以上版本
                        Intent mediaScanIntent = new Intent(
                                Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                        Uri contentUri = Uri.fromFile(new File(DownLoadManager.getSDPath())); //out is your output file
                        mediaScanIntent.setData(contentUri);
                        sendBroadcast(mediaScanIntent);
                    } else {
                        sendBroadcast(new Intent(
                                Intent.ACTION_MEDIA_MOUNTED,
                                Uri.parse(DownLoadManager.getSDPath())));
                    }
                });
            }
        });
    }


    /**
     * @param context
     * @param targetFile 要保存的照片文件
     * @param path  要保存的照片的路径地址
     */
    public static void addMediaStore(Context context, File targetFile, String path) {

        ContentResolver resolver = context.getContentResolver();
        ContentValues newValues = new ContentValues(5);
        newValues.put(MediaStore.Images.Media.DISPLAY_NAME, targetFile.getName());
        newValues.put(MediaStore.Images.Media.DATA, targetFile.getPath());
        newValues.put(MediaStore.Images.Media.DATE_MODIFIED, System.currentTimeMillis() / 1000);
        newValues.put(MediaStore.Images.Media.SIZE, targetFile.length());
        newValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");

        resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, newValues);
        MediaScannerConnection.scanFile(context, new String[]{path}, null, null);//刷新相册
    }
    private void checkPermission() {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_CODE);//requesrCode
            } else {
            }
        } else {
        }


    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE) {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] == 0) {
                    ToastUtil.showShortToast(this, "获取权限成功");
                } else {
                    ToastUtil.showShortToast(this,"获取权限失败");
                }
            }
        }
    }


}